<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="header">
        <el-page-header @back="goBack" content="商品详情" />
        <div class="actions">
          <el-button v-if="form.status === 1" type="danger" @click="handleDelist">下架</el-button>
          <el-button v-else type="success" @click="handleList">上架</el-button>
        </div>
      </div>

      <el-tabs v-model="activeTab">
        <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>商品分类：</label>
                <span>{{ form.categoryName }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="info-item">
                <label>商品名称：</label>
                <span>{{ form.productName }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="info-item">
                <label>商品卖点：</label>
                <span>{{ form.sellingPoint }}</span>
              </div>
            </el-col>
          </el-row>
        <el-row>
            <el-col :span="12">
              <div class="info-item">
                <label>商品编号：</label>
                <span>{{ form.productSn }}</span>
              </div>
            </el-col>
          </el-row>

        <el-col :span="24">
          <div class="info-item">
            <label>商品参数：</label>
            <span v-html="form.productParams" class="product-specs"></span>
          </div>
        </el-col>

        <el-col :span="24">
          <div class="info-item">
            <label>商品详情：</label>
            <span v-html="form.description" class="product-specs"></span>
          </div>
        </el-col>

        <h2 class="section-title">商品信息</h2>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>计量单位：</label>
                <span>{{ form.productUnit }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>销售模式：</label>
                <el-tag :type="form.salesModel === 'retail' ? 'warning' : 'info'">
                  {{ form.salesModel === 'retail' ? '零售' : '批发' }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>销售价格：</label>
                <span>¥{{ form.price }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>成本价格：</label>
                <span>¥{{ form.costPrice }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>市场价：</label>
                <span>¥{{ form.originalPrice }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>库存：</label>
                <span>{{ form.stock }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>已售数量：</label>
                <span>{{ form.soldNum }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>商品重量：</label>
                <span>{{ form.weight }}kg</span>
              </div>
            </el-col>
          </el-row>

        <h2 class="section-title">商品规格及图片</h2>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="info-item">
                <label>商品规格：</label>
                <span v-html="form.specs" class="product-specs"></span>
              </div>
            </el-col>
          </el-row>

        <h2 class="section-title">商品详情描述</h2>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>商品卖点：</label>
              <span>{{ form.sellingPoint }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>商品描述：</label>
              <span>{{ form.description }}</span>
            </div>
          </el-col>
        </el-row>

        <el-divider content-position="left">商品主图</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="image-section">
                <div class="image-display" v-if="form.mainImage">
                  <el-image
                      style="width: 200px; height: 200px; margin-right: 10px;"
                      :src="form.mainImage"
                      :preview-src-list="[form.mainImage]"
                      fit="cover"
                  />
                </div>
                <div class="image-upload">
                  <image-upload 
                    v-model="form.mainImage" 
                    :limit="1" 
                    :file-size="5"
                    :file-type="['png', 'jpg', 'jpeg', 'gif']"
                    @update:modelValue="handleMainImageChange"
                  />
                  <div class="upload-tip">请上传商品主图，建议尺寸800x800px，支持PNG、JPG、JPEG、GIF格式</div>
                </div>
              </div>
            </el-col>
          </el-row>

          <el-divider content-position="left">商品相册</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="image-section">
                <div class="image-display" v-if="form.imageGallery">
                  <div class="gallery-header">
                    <span class="gallery-count">共 {{ form.imageGallery.split(',').length }} 张图片</span>
                  </div>
                  <div class="gallery-images">
                    <el-image
                        v-for="(img, index) in form.imageGallery.split(',')"
                        :key="index"
                        style="width: 120px; height: 120px; margin-right: 10px;"
                        :src="img"
                        :preview-src-list="form.imageGallery.split(',')"
                        fit="cover"
                    />
                  </div>
                </div>
                <div class="image-upload">
                  <image-upload 
                    v-model="form.imageGallery" 
                    :limit="10" 
                    :file-size="5"
                    :file-type="['png', 'jpg', 'jpeg', 'gif']"
                    @update:modelValue="handleGalleryChange"
                  />
                  <div class="upload-tip">请上传商品相册图片，最多10张，建议尺寸800x800px，支持PNG、JPG、JPEG、GIF格式</div>
                </div>
              </div>
            </el-col>
          </el-row>

          <el-divider content-position="left">商品视频</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="video-section">
                <div class="video-display" v-if="form.productVideo">
                  <div class="video-header">
                    <span class="video-count">商品视频</span>
                  </div>
                  <div class="video-content">
                    <video 
                      :src="form.productVideo" 
                      controls 
                      style="width: 300px; height: 200px;"
                      preload="metadata"
                    ></video>
                  </div>
                </div>
                <div class="video-upload">
                  <video-upload 
                    v-model="form.productVideo" 
                    :limit="1" 
                    :file-size="200"
                    :file-type="['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm']"
                    @update:modelValue="handleVideoChange"
                  />
                  <div class="upload-tip">请上传商品视频，最多1个，大小不超过200MB，支持MP4、AVI、MOV、WMV、FLV、WEBM格式</div>
                </div>
              </div>
            </el-col>
          </el-row>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getPlatform, listProduct, delistProduct, updatePlatform } from '@/api/shangpin/platform'
import { ElMessage } from 'element-plus'
import VideoUpload from '@/components/VideoUpload/index.vue'

const route = useRoute()
const router = useRouter()

const activeTab = ref('basic')
const form = ref({
  id: null,
  productName: '',
  productSn: '',
  productUnit: '',
  description: '',
  sellingPoint: '',
  price: 0,
  costPrice: 0,
  originalPrice: 0,
  stock: 0,
  soldNum: 0,
  weight: 0,
  mainImage: '',
  imageGallery: '',
  productVideo: '',
  status: 0,
  categoryName: '',
  salesModel: '',
  productParams: '',
  specs: ''
})

// 获取商品详情
const getDetail = () => {
  const id = route.query.id || route.params.id
  getPlatform(id).then(response => {
    form.value = response.data
  })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 上架商品
const handleList = () => {
  listProduct(form.value.id).then(() => {
    getDetail()
  })
}

// 下架商品
const handleDelist = () => {
  delistProduct(form.value.id).then(() => {
    getDetail()
  })
}

// 主图变化处理
const handleMainImageChange = async (value) => {
  try {
    if (value) {
      // 确保value是字符串格式
      let imageUrl = value
      if (typeof value === 'object' && value.url) {
        imageUrl = value.url
      } else if (Array.isArray(value) && value.length > 0) {
        imageUrl = value[0].url || value[0]
      }
      
      const updateData = {
        id: form.value.id,
        mainImage: imageUrl
      }
      
      await updatePlatform(updateData)
      ElMessage.success('主图更新成功')
    }
  } catch (error) {
    console.error('更新主图失败:', error)
    ElMessage.error('更新主图失败：' + (error.message || '未知错误'))
  }
}

// 相册变化处理
const handleGalleryChange = async (value) => {
  try {
    let imageUrls = ''
    if (value) {
      if (Array.isArray(value)) {
        // 如果是数组，提取所有URL并用逗号连接
        imageUrls = value.map(item => {
          if (typeof item === 'object' && item.url) {
            return item.url
          }
          return item
        }).join(',')
      } else if (typeof value === 'string') {
        imageUrls = value
      }
    }
    
    const updateData = {
      id: form.value.id,
      imageGallery: imageUrls
    }
    
    await updatePlatform(updateData)
    ElMessage.success('相册更新成功')
  } catch (error) {
    console.error('更新相册失败:', error)
    ElMessage.error('更新相册失败：' + (error.message || '未知错误'))
  }
}

// 视频变化处理
const handleVideoChange = async (value) => {
  try {
    let videoUrl = ''
    if (value) {
      if (Array.isArray(value) && value.length > 0) {
        // 如果是数组，取第一个视频的URL
        videoUrl = value[0].url || value[0]
      } else if (typeof value === 'string') {
        videoUrl = value
      }
    }
    
    const updateData = {
      id: form.value.id,
      productVideo: videoUrl
    }
    
    await updatePlatform(updateData)
    ElMessage.success('视频更新成功')
  } catch (error) {
    console.error('更新视频失败:', error)
    ElMessage.error('更新视频失败：' + (error.message || '未知错误'))
  }
}

onMounted(() => {
  getDetail()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.info-item {
  margin-bottom: 15px;
  line-height: 32px;
  font-size: 14px;
}

.info-item label {
  font-weight: bold;
  color: #606266;
  min-width: 100px;
  display: inline-block;
}

.info-item span {
  color: #303133;
}

.product-params,
.product-detail,
.product-specs {
  padding: 10px;
  margin-left: -10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.image-section {
  margin-bottom: 20px;
}

.image-display {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.image-upload {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #d9d9d9;
}

.image-upload:hover {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.upload-tip {
  margin-top: 15px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.gallery-header {
  margin-bottom: 15px;
  padding: 8px 12px;
  background-color: #f0f8ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.gallery-count {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.gallery-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.video-section {
  margin-bottom: 20px;
}

.video-display {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.video-header {
  margin-bottom: 15px;
  padding: 8px 12px;
  background-color: #f0f8ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.video-count {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.video-content {
  text-align: center;
}

.video-upload {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #d9d9d9;
}

.video-upload:hover {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}
</style>